package com.dss.sdk.utils.url;

import com.dss.sdk.utils.string.StrUtil;

import java.util.HashMap;

/**
 * url工具类
 */
public abstract class DssUrlUtils {
    /**
     * 等到请求url
     */
    public static String getServerUrl(String serverUrl, String apiMethodName, String session, HashMap appParams) {
        if (apiMethodName.indexOf(StrUtil.SLASH) > 0) {
            apiMethodName = StrUtil.SLASH + apiMethodName;
        }
        String host = serverUrl.lastIndexOf(StrUtil.SLASH) == 0 ? replaceLast(serverUrl, StrUtil.SLASH, StrUtil.EMPTY) : serverUrl;
        return host + apiMethodName;
    }

    public static String buildRequestUrl(String url, String... queries) {
        if (queries == null || queries.length == 0) {
            return url;
        }
        StringBuilder newUrl = new StringBuilder(url);
        boolean hasQuery = url.contains("?");
        boolean hasPrepend = url.endsWith("?") || url.endsWith("&");
        for (String query : queries) {
            if (!StrUtil.isEmpty(query)) {
                if (!hasPrepend) {
                    if (hasQuery) {
                        newUrl.append("&");
                    } else {
                        newUrl.append("?");
                        hasQuery = true;
                    }
                }
                newUrl.append(query);
                hasPrepend = false;
            }
        }
        return newUrl.toString();
    }

    /**
     * 替换字符串里最后出现的元素
     */
    private static String replaceLast(String text, String strToReplace,
                                      String replaceWithThis) {
        return text.replaceFirst("(?s)" + strToReplace + "(?!.*?" + strToReplace
                + ")", replaceWithThis);
    }
}
